<template>
    <div class='app-container'>
        <el-dialog v-model="isShow" size="50%" style="height: 600px" :destroy-on-close="true" @close="closeHandle"
            :close-on-press-escape="false" :close-on-click-modal="false" :show-close="false">
            <template #header>
                <h4>监控回放</h4>
            </template>
            <div style="height: 430px;width: 100%" v-loading="dialogloading">
                <Playback :playUrl="playerUrl" @close="closeHandle"></Playback>
            </div>
        </el-dialog>
        <el-row :gutter="20" style="height:calc(100% - 40px);">
            <el-col :span="4" style="height: 500px; overflow-y:auto;">
                <div class="head-container mb-3">
                    <el-input placeholder="输入关键字进行过滤" v-model="filterText">
                    </el-input>
                </div>
                <div class="head-container" v-loading="loadingdeptOptions">
                    <el-tree :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                        :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id"
                        highlight-current @node-click="handleNodeClick" />
                </div>
            </el-col>
            <el-col :span="19">
                <el-form ref="formRef" style="width:100%" :rules="rules" :inline="true" :model="form">
                    <el-row :gutter="20" class="mb-3" style="width:100%">
                        <el-col :span="8">
                            <el-form-item label="选择单位" required prop="unitId">
                                <el-tree-select v-model="form.unitId" :data="UnitOptions"
                                    :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                                    placeholder="选择单位" check-strictly @change="handleNodeClickUnit" default-expand-all
                                    style="width:220px" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="选择时间" required prop="period">
                                <el-date-picker v-model="form.period" type="date" placeholder="请选择时间"
                                    value-format="YYYYMMDD" format="YYYY-MM-DD" @change="getLists" />
                                <!-- 
                                    @clear="getLists" -->
                            </el-form-item>
                        </el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getLists">
                                <el-icon class="me-1">
                                    <Search />
                                </el-icon>
                                查询
                            </el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="handleRest">
                                <el-icon class="me-1">
                                    <Refresh />
                                </el-icon>
                                重置
                            </el-button>
                        </el-form-item>
                    </el-row>
                </el-form>

                <el-table ref="roomTableRef" v-loading="loading" :data="TableData" border
                stripe
            :row-style="tableRowStyle">
                    <el-table-column label="录像名称" prop="name" />
                    <el-table-column label="开始时间" :formatter="formatStartTime" />

                    <el-table-column label="播放时长" :formatter="formatDuration" />
                    <el-table-column label="结束时间" :formatter="formatEndTime" />
                    <el-table-column fixed="right" label="操作" width="110" align="center">
                        <template #default="scope">
                            <el-button link size="small" type="primary" @click="playvideo(scope.row)">
                                <el-icon class="me-1">
                                    <Edit />
                                </el-icon>
                                播放
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- {{ paging.limit }}paging.limit ---v-model:page="paging.limit"
                <br>
                {{ paging.start }}paging.start--v-model:limit="paging.start"  -->
                <pagination v-show="total > 0" v-model:limit="paging.limit" v-model:page="paging.start" :total="total"
                    @pagination="getLists" />
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { getunitDeviceChannelTree } from "@/api/ParameterSetting/Device";
import { listDept } from "@/api/system/dept";
import Playback from "@/views/monitor1/playback/components/playback.vue";
import { queryDaily, videoplayback } from "@/api/videoApi/videoApi";
import PageEnum from "@/enum/PageEnum.js";

export default {
    name: '',
    components: {
        //组件
        Playback
    },
    data() {
        return {
            dialogloading: true,
            loading: false,
            loadingdeptOptions: false,
            isShow: false,
            form: {},
            filterText: '',
            TableData: [],
          
            paging: { start: 2, limit: PageEnum.SIZE },
            total: 0,
            queryParams: {},
            playQuery: {},
            UnitOptions: [],
            deptOptions: [],
            playerUrl: '',
            rules: {
                period: [{ required: true, message: "时间不能为空", trigger: "change" }],
                unitId: [{ required: true, message: "单位不能为空", trigger: "change" }],
            },
        };
    },
    mounted() {
        this.getDeptTree();
    },
    watch: {
        filterText(val) {
            this.$refs.deptTreeRef.filter(val);
        }
    },
    methods: {
        tableRowStyle({ row, rowIndex }){
            if (rowIndex % 2 === 0) {
                return { backgroundColor: '#e6ecff' }; // 偶数行背景色
            }
            return {}; // 奇数行默认透明
        },
        /** 通过条件过滤节点  */
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        playvideo(row) {
            this.playQuery.monitorServerId = this.queryParams.monitorServerId
            this.playQuery.channelId = this.queryParams.channelId
            this.playQuery.file = row.name
            this.playQuery.sTime = this.formatStartTime(row)
            this.playQuery.eTime = this.formatEndTime(row)
            this.isShow = true;
            videoplayback(this.playQuery).then(res => {
                this.dialogloading = false
                this.playerUrl = res.data.prefix + res.data.EasyDarwin.Body.URL
            });


        },
        getDeptTree() {
            this.loading = true;
            listDept().then(res => {
                this.UnitOptions = res.data.filter(item => item.isUnit === true);
                this.UnitOptions = this.handleTree(this.UnitOptions, "deptId");
                console.log(this.UnitOptions)
                this.loading = false;
            });
        },

        handleNodeClickUnit(data) {
            this.getunitDeviceChannelTreeList(data);
        },
        handleNodeClick(data) {
            console.log(data.monitorserverId)
            if (data.monitorserverId === '' || data.monitorserverId == null || data.monitorserverId == undefined) {
                ElMessage.warning('请选择通道');
            } else {
                this.queryParams = {
                    start: this.paging.start,
                    limit: this.paging.limit,
                    monitorServerId: data.monitorserverId,
                    channelId: data.channels,
                    recordType: 'Device',
                    period: this.form.period,
                }
                this.getLists()
            }

        },
        getLists() {
            this.$refs.formRef.validate(valid => {
                if (valid) {
                    if (this.queryParams.monitorServerId == '' || this.queryParams.monitorServerId == null) {
                        ElMessage.warning('请选择左边通道');
                    } else {
                        this.loading = true;
                        this.queryParams.period = this.form.period
                        this.queryParams.start = this.paging.start
                        this.queryParams.limit = this.paging.limit
                        queryDaily(this.queryParams).then(res => {
                            this.TableData = res.data.list
                            this.total = res.data.total
                            this.loading = false;
                        });
                    }
                }
            });
        },
        getunitDeviceChannelTreeList(UnitId) {
            this.loadingdeptOptions = true;
            this.deptOptions = [];
            getunitDeviceChannelTree(UnitId).then(res => {
                const transformRoomTypes = (roomTypes) => {
                    return roomTypes.map(room => {
                        const transformedRoom = {
                            ...room,
                            label: room.label || room.roomname,
                            id: room.id || room.roomId
                        };
                        if (room.baseMonitorChannels) {
                            transformedRoom.children = room.baseMonitorChannels.map(channel => ({
                                ...channel,
                                label: channel.label || channel.channelname,
                                id: channel.id || channel.channelcode
                            }));
                            delete transformedRoom.baseMonitorChannels;
                        }
                        if (room.children && room.children.length > 0) {
                            transformedRoom.children = transformRoomTypes(room.children);
                        }
                        return transformedRoom;
                    });
                };
                if (res.data && Array.isArray(res.data) && res.data[0] && res.data[0].roomTypes) {
                    var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
                    var videoTypesdata = res.data[0].videoTypes;
                    videoTypesdata.forEach(videoType => {
                        videoType.children.forEach(channel => {
                            channel.label = channel.label || channel.channelname;
                            channel.id = channel.monitorchannelsId || channel.channelcode;
                        });
                    });
                    this.deptOptions = [...roomTypesdata, ...videoTypesdata];
                } else {
                    ElMessage.error('当前单位无监控节点');
                }
                this.loadingdeptOptions = false;
            });
        },
        closeHandle() {
            this.isShow = false;
            this.getLists();
        },
        handleRest() {
            console.log(1111);
            this.getLists();
        },
        // 时间格式化
        formatStartTime(row) {
            return this.formatDate(row.startAt);
        },
        formatDuration(row) {
            return this.secondsToHMS(row.duration);
        },
        formatEndTime(row) {
            if (!row.startAt) return '无开始时间';
            // 将开始时间格式化为 Date 对象
            const startDate = new Date(
                parseInt(row.startAt.substring(0, 4)),    // 年
                parseInt(row.startAt.substring(4, 6)) - 1, // 月（0-11）
                parseInt(row.startAt.substring(6, 8)),    // 日
                parseInt(row.startAt.substring(8, 10)),   // 时
                parseInt(row.startAt.substring(10, 12)),  // 分
                parseInt(row.startAt.substring(12, 14))   // 秒
            );

            // 计算结束时间
            const endDate = new Date(startDate.getTime() + row.duration * 1000);
            // 格式化结束时间为 'YYYY-MM-DD HH:mm:ss' 格式
            return this.formatDateFromObject(endDate);
        },

        formatDateFromObject(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        formatDate(dateString) {
            const year = dateString.substring(0, 4);
            const month = dateString.substring(4, 6);
            const day = dateString.substring(6, 8);
            const hour = dateString.substring(8, 10);
            const minute = dateString.substring(10, 12);
            const second = dateString.substring(12, 14);
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        },
        secondsToHMS(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;

            return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
        }
    },
};
</script>
